package cn.itsource.pethome.basic.service.impl;

import cn.itsource.pethome.basic.constant.PetHomeConstant;
import cn.itsource.pethome.basic.service.IVerificationCodeService;
import cn.itsource.pethome.basic.util.SendMsgUtil;
import cn.itsource.pethome.basic.util.StrUtils;
import org.junit.rules.Timeout;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Service
@Transactional(readOnly = false,propagation = Propagation.SUPPORTS)
public class VerificationCodeServiceImpl implements IVerificationCodeService {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void sendRegisterMobileCode(String phone) {
        //产生随机6位验证码
        String code = StrUtils.getComplexRandomString(6);
        //通过手机号码在redis中获取对应的验证码
        String codeValue  =(String) redisTemplate.opsForValue().get(PetHomeConstant.REGISTER_VERIFICATION_CODE + ":" + phone);
        if(!StringUtils.isEmpty(codeValue)){
            //获取第一次的毫秒时间
            Long beginTimer = Long.valueOf(codeValue.split(":")[1]);
            if(System.currentTimeMillis()-beginTimer<60*1000){
                throw new RuntimeException("一分钟内不能频繁发送");
            }
            //如果没有抛异常说明在1分钟外5分钟内
             code = codeValue.split(":")[0];
        }
        //将验证码放入redis中，并且有效期是5分钟
        redisTemplate.opsForValue().set(PetHomeConstant.REGISTER_VERIFICATION_CODE+":"+phone,code+":"+System.currentTimeMillis());

        String content = "尊敬的用户，您的验证码为："+code+",请在5分钟内完成操作";
        SendMsgUtil.sendMsg(phone,content);

    }

}
